package Xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 26.11.13
 * Time: 14:33
 * To change this template use File | Settings | File Templates.
 */
public class XmlUserWriter {
    private String filePath = "C:\\JAVA\\src\\Xml\\Users.xml";
    private Document document;

    /**
     * Метод дописать юзера в файл.
     * @param login
     * @param password
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     * @throws TransformerException
     */
    public void addNewUser(String login, String password) throws IOException,
            SAXException, ParserConfigurationException, TransformerException {
        this.loadDocument();
        Node root = document.getFirstChild();
        Element user = document.createElement("user");
        Element log = document.createElement("login");
        log.appendChild(document.createTextNode(login));
        Element pass = document.createElement("password");
        pass.appendChild(document.createTextNode(password));
        user.appendChild(log);
        user.appendChild(pass);
        root.appendChild(user);
        transformDocument();
    }

    private void loadDocument() throws ParserConfigurationException, IOException, SAXException {
        File xmlFile = new File(filePath);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.parse(xmlFile);
        document.getDocumentElement().normalize();
    }

    private void transformDocument() throws TransformerException {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource domSource = new DOMSource(document);
        StreamResult streamResult = new StreamResult(new File(filePath));
        transformer.transform(domSource, streamResult);
    }
}
